package com.sky.module.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sky.utils.Result;
import com.sky.utils.ResultCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 认证用户访问无权限 处理类
 *
 * @date 2023/2/20 10:16
 **/
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");

//        保存异常信息
        final ServletOutputStream outputStream = response.getOutputStream();
//        if (exception instanceof AccountExpiredException) {
//            message = "账户过期，登录失败";
//
//        } else if (exception instanceof BadCredentialsException) {
//            message = "用户名或密码错误，登录失败";
//        } else if (exception instanceof CredentialsExpiredException) {
//            message = "密码过期，登录失败";
//        } else if (exception instanceof DisabledException) {
//            message = "账户过期，登录失败";
//        } else if (exception instanceof LockedException) {
//            message = "账户被锁定，登录失败";
//        } else if (exception instanceof InternalAuthenticationServiceException) {
//            message = "账户不存在,登录失败";
//        } else {
//            message = "登录失败";
//        }
//        将结果转成json格式 消除循环引用
        String result = JSON.toJSONString(Result.error().code(ResultCode.NO_AUTH).message("无权限访问，请联系管理员")
                , SerializerFeature.DisableCircularReferenceDetect);
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
